<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <!-- <sticky :z-index="10" :class-name="'sub-navbar '+postForm.status"> -->
      <sticky :z-index="10" class="sub-navbar">
        <!-- <CommentDropdown v-model="postForm.comment_disabled" /> -->
        <!-- <PlatformDropdown v-model="postForm.platforms" /> -->
        <!-- <SourceUrlDropdown v-model="postForm.source_uri" /> -->
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          发布
        </el-button>
        <!-- <el-button v-loading="loading" type="warning" @click="draftForm">
          Draft
        </el-button> -->
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <!-- <Warning /> -->

          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="postForm.title" :maxlength="100" name="name" required>
                视频名称
              </MDinput>
            </el-form-item>

            <!-- <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="60px" label="Author:" class="postInfo-container-item">
                    <el-select v-model="postForm.author" :remote-method="getRemoteUserList" filterable default-first-option remote placeholder="Search user">
                      <el-option v-for="(item,index) in userListOptions" :key="item+index" :label="item" :value="item" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="10">
                  <el-form-item label-width="120px" label="Publish Time:" class="postInfo-container-item">
                    <el-date-picker v-model="displayTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="Select date and time" />
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label-width="90px" label="Importance:" class="postInfo-container-item">
                    <el-rate
                      v-model="postForm.importance"
                      :max="3"
                      :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                      :low-threshold="1"
                      :high-threshold="3"
                      style="display:inline-block"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div> -->
          </el-col>
        </el-row>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="视频简介">
          <el-input v-model="postForm.description" :rows="1" type="textarea" class="article-textarea" autosize placeholder="输入视频简介" />
          <span v-show="descriptionLength" class="word-counter">{{ descriptionLength }} 字</span>
        </el-form-item>

        <!-- <el-form-item prop="content" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="postForm.content" :height="400" />
        </el-form-item> -->

        <el-form-item style="margin-bottom: 30px;" label-width="70px" label="视频文件">
          <div style="width:200px;height:200px;position:relative;">
            <el-input ref="videoFile" v-model="postForm.video_file" type="file" class="videoFile" :rows="1" style="opacity:0;width:100%;height:100%;position:absolute;top:0;left:0" @change="changeVideo" />
            <img style="max-width:100%;max-height:100%;" :src="coverUrl">
          </div>
        </el-form-item>

        <el-form-item style="margin-bottom: 30px;" label-width="70px" label="视频预览">
          <!-- <div style="width:200px;height:200px;position:relative;">
            <el-input ref="videoFile" v-model="postForm.video_file" type="file" class="videoFile" :rows="1" accept="image/jpeg,image/jpg,image/png" style="opacity:0;width:100%;height:100%;position:absolute;top:0;left:0" @change="changeCover" />
            <img style="max-width:100%;max-height:100%;" :src="coverUrl">
          </div> -->
          <video ref="playVideo" style="width: 400px;" controls="controls" />
        </el-form-item>

        <el-form-item style="margin-bottom: 30px;" label-width="70px" label="封面文件">
          <div style="width:200px;height:200px;position:relative;">
            <el-input ref="coverFile" v-model="postForm.cover_file" type="file" class="coverFile" :rows="1" accept="image/jpeg,image/jpg,image/png" style="opacity:0;width:100%;height:100%;position:absolute;top:0;left:0" @change="changeCover" />
            <img ref="coverUrl" style="max-width:100%;max-height:100%;" :src="coverUrl">
          </div>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
// import Tinymce from '@/components/Tinymce'
// import Upload from '@/components/Upload/SingleImage2'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
// import { validURL } from '@/utils/validate'
import { fetchVideo, createVideo, updateVideo } from '@/api/video'
// import { searchUser } from '@/api/remote-search'
// import Warning from './Warning'
// import { CommentDropdown, PlatformDropdown, SourceUrlDropdown } from './Dropdown'

const defaultForm = {
  // status: 'draft',
  title: '', // 视频标题// 文章题目
  // content: '', // 文章内容
  // content_short: '', // 文章摘要
  description: '', // 视频描述
  // source_uri: '', // 文章外链
  // image_uri: '', // 文章图片
  video_file: undefined, // 视频文件
  url: '', // 视频链接
  cover_file: undefined, // 视频封面图片文件
  cover_url: '', // 视频封面图片链接
  // display_time: undefined, // 前台展示时间
  id: undefined
  // platforms: ['a-platform'],
  // comment_disabled: false,
  // importance: 0
}

export default {
  name: 'VideoDetail',
  // components: { Tinymce, MDinput, Upload, Sticky, Warning, CommentDropdown, PlatformDropdown, SourceUrlDropdown },
  components: { MDinput, Sticky },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          // message: rule.field + '必须',
          message: this.mapper[rule.field] + '必须',
          type: 'error'
        })
        // callback(new Error(rule.field + '必须'))
        callback(new Error(this.mapper[rule.field] + '必须'))
      } else {
        callback()
      }
    }
    // const validateSourceUri = (rule, value, callback) => {
    //   if (value) {
    //     if (validURL(value)) {
    //       callback()
    //     } else {
    //       this.$message({
    //         message: '外链url填写不正确',
    //         type: 'error'
    //       })
    //       callback(new Error('外链url填写不正确'))
    //     }
    //   } else {
    //     callback()
    //   }
    // }
    return {
      mapper: { title: '视频名称' },
      postForm: Object.assign({}, defaultForm),
      loading: false,
      // userListOptions: [],
      rules: {
        // image_uri: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }]
        // content: [{ validator: validateRequire }],
        // source_uri: [{ validator: validateSourceUri, trigger: 'blur' }]
      },
      tempRoute: {},
      coverUrl: 'http://psbc.jumpcity.cm/static/image/upload.png'
    }
  },
  computed: {
    descriptionLength() {
      return this.postForm.description.length
    }
    // displayTime: {
    //   // set and get is useful when the data
    //   // returned by the back end api is different from the front end
    //   // back end return => "2013-06-25 06:59:25"
    //   // front end need timestamp => 1372114765000
    //   get() {
    //     return (+new Date(this.postForm.display_time))
    //   },
    //   set(val) {
    //     this.postForm.display_time = new Date(val)
    //   }
    // }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    // 修改时才会执行该方法
    fetchData(id) {
      fetchVideo(id).then(response => {
        this.postForm = response.data

        // just for test
        // this.postForm.title += `   Article Id:${this.postForm.id}`
        // this.postForm.content_short += `   Article Id:${this.postForm.id}`

        // set tagsview title
        this.setTagsViewTitle()

        // set page title
        this.setPageTitle()

        if (this.postForm.url !== '' && this.postForm.url !== null) {
          this.$refs.playVideo.src = this.postForm.url
        }
        if (this.postForm.cover_url !== '' && this.postForm.cover_url !== null) {
          this.$refs.coverUrl.src = this.postForm.cover_url
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 修改时才会执行该方法
    setTagsViewTitle() {
      const title = '修改视频'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    // 修改时才会执行该方法
    setPageTitle() {
      const title = '修改视频'
      document.title = `${title} - ${this.postForm.id}`
    },
    submitForm() {
      console.log('src/views/video/components/VideoDetail.vue submitForm() this.postForm')
      console.log(this.postForm)
      // this.$refs.postForm.validate(valid => {
      //   if (valid) {
      //     this.loading = true
      //     this.$notify({
      //       title: '成功',
      //       message: '发布视频成功',
      //       type: 'success',
      //       duration: 2000
      //     })
      //     this.postForm.status = 'published'
      //     this.loading = false
      //   } else {
      //     console.log('error submit!!')
      //     return false
      //   }
      // })
      // this.postForm.video_file = new File(this.postForm.video_file)
      // this.postForm.cover_file = new File(this.postForm.cover_file)

      var formData = new FormData()
      formData.append('title', this.postForm.title)
      formData.append('description', this.postForm.description)

      if (this.$refs.videoFile.$refs.input.files.length > 0) {
        formData.append('video_file', this.$refs.videoFile.$refs.input.files[0])
      }

      if (this.$refs.coverFile.$refs.input.files.length > 0) {
        formData.append('cover_file', this.$refs.coverFile.$refs.input.files[0])
      }

      if (this.postForm.id) {
        formData.append('id', this.postForm.id)
        updateVideo(formData)
          .then(data => {
            console.log('updateVideo then data')
            console.log(data)
            this.loading = true
            this.$notify({
              title: '成功',
              message: '发布视频成功',
              type: 'success',
              duration: 2000
            })
            // this.postForm.status = 'published'
            this.loading = false
          })
          .catch(err => {
            console.log('updateVideo then err')
            console.log(err)
          })
      } else {
        createVideo(formData)
          .then(data => {
            console.log('createVideo then data')
            console.log(data)
            this.loading = true
            this.$notify({
              title: '成功',
              message: '发布视频成功',
              type: 'success',
              duration: 2000
            })
            // this.postForm.status = 'published'
            this.loading = false
          })
          .catch(err => {
            console.log('createVideo then err')
            console.log(err)
          })
      }

      // upload(formData)
      //   .then(data => {
      //     console.log('upload then data')
      //     console.log(data)
      //   })
      //   .catch(err => {
      //     console.log('upload then err')
      //     console.log(err)
      //     console.log('请求失败处理')
      //   })
    },
    changeVideo() {
      // console.log(arguments);
      // console.log(this.$refs.videoFile)
      // console.log(this.$refs.coverFile.$refs)
      // console.log(this.$refs.coverFile.$refs.input)
      // console.log(this.$refs.videoFile.$refs.input.files)
      // console.log(this.$refs.coverUrl)
      this.$refs.playVideo.src = window.URL.createObjectURL(this.$refs.videoFile.$refs.input.files[0])
      // this.$refs.coverUrl.srcObject = this.$refs.coverFile.$refs.input.files[0]
    },
    changeCover() {
      // console.log(arguments);
      // console.log(this.$refs.coverFile)
      // console.log(this.$refs.coverFile.$refs)
      // console.log(this.$refs.coverFile.$refs.input)
      // console.log(this.$refs.coverFile.$refs.input.files)
      // console.log(this.$refs.coverUrl)
      this.$refs.coverUrl.src = window.URL.createObjectURL(this.$refs.coverFile.$refs.input.files[0])
      // this.$refs.coverUrl.srcObject = this.$refs.coverFile.$refs.input.files[0]
    }
    // draftForm() {
    //   if (this.postForm.content.length === 0 || this.postForm.title.length === 0) {
    //     this.$message({
    //       message: '请填写必要的标题和内容',
    //       type: 'warning'
    //     })
    //     return
    //   }
    //   this.$message({
    //     message: '保存成功',
    //     type: 'success',
    //     showClose: true,
    //     duration: 1000
    //   })
    //   this.postForm.status = 'draft'
    // },
    // getRemoteUserList(query) {
    //   searchUser(query).then(response => {
    //     if (!response.data.items) return
    //     this.userListOptions = response.data.items.map(v => v.name)
    //   })
    // }
  }
}

// .article-textarea /deep/ {
</script>

<style lang="scss">
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}

.coverFile .el-input__inner, .videoFile .el-input__inner {
  width: 100%;
  height: 100%;
}
</style>
